<template>
  <div class="menulist">
    <jc-button
      :btn-arr="[bomCost('per:insertExRate') && 'newy', 'sub', 'option', 'remove','pass']"
      :disab-arr="['close', 'copy', 'cancel', 'freeze', 'com1', 'com2', 'using', 'chart']"
      @del="removeRate"
      @newly="addRate"
      @submit="submitRate(1)"
      @noSubmit="submitRate(2)"
      @audit="auditRate(1)"
      @noAudit="auditRate(2)"
      @toExcel="handleExport"
    />
    <div class="header">
      <div class="header-name">
        <search
          :options="selectData"
          :msg="tacitly"
          @seek="collect"
          @hand="searchMaterialList"
        />
        <el-button size="mini" type="primary" class="btn" @click="searchMaterialList">
          {{ $t('btn.search') }}
        </el-button>
      </div>
    </div>
    <div class="rateContent">
      <div class="sibarLeft">
        <div>
          <el-button :disabled="!bomCost('per:insertExGroup')" type="primary" size="mini" @click.native="addGroup">
            {{ $t('market.addGroup') }}<!--新增分组-->
          </el-button>
          <el-button type="danger" size="mini" @click.native="delGroup">
            {{ $t('market.delGroup') }}<!--删除分组-->
          </el-button>
          <el-button type="warning" size="mini" @click.native="editGroup">
            {{ $t('market.editGroup') }}<!--编辑分组-->
          </el-button>
        </div>
        <el-tree
          ref="tree"
          :data="treeData"
          :props="defaultProps"
          node-key="fgroupId"
          :default-expanded-keys="[0]"
          highlight-current
          :expand-on-click-node="false"
          @node-click="handleNodeClick"
        />
      </div>
      <div class="table-content">
        <jc-table
          sortable
          :table-data="tableData"
          :table-header="tableHeader"
          :table-height="tableHeight"
          table-selection
          get-row-keys="fid"
          @selectionChange="selectionDatas"
        >
          <template v-slot:tagSlot="col">
            <el-tag :type="col.scope.row.stateColor">{{ col.scope.row.fdocumentstatus }}</el-tag>
          </template>
          <template v-slot:btnSlot="col">
            <el-button type="warning" size="mini" @click="editCurr(col.scope.row)">{{ $t('btn.edit') }}</el-button>
          </template>
        </jc-table>
        <div class="footer">
          <jc-pagination
            v-show="total > 0"
            :total="total"
            :page.sync="currentPage"
            :limit.sync="size"
            @pagination="getRateList"
          />
        </div>
      </div>
    </div>
    <!--  汇率组别  -->
    <el-dialog
      v-dialogDrag
      :title="rateTitle"
      model
      :visible.sync="rateVisable"
      :close-on-click-modal="false"
      width="500px"
    >
      <el-form label-width="100px" :model="groupData">
        <el-form-item :label="$t('market.groupname')">
          <el-input v-model="groupData.fgroupName" size="mini" />
        </el-form-item>
        <el-form-item :label="$t('market.groupnum')">
          <el-input v-model="groupData.fnumber" size="mini" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="rateVisable = false">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" @click="insertGroup">{{ $t('btn.confirm') }}</el-button>
      </div>
    </el-dialog>
    <!--  新增/修改汇率  -->
    <el-dialog
      v-dialogDrag
      :title="rateTitle1"
      model
      center
      :visible.sync="rateListVisable"
      :close-on-click-modal="false"
      width="400px"
    >
      <el-form label-width="100px" :model="rateData">
        <el-form-item :label="$t('market.exchangeType')" prop="fgroupId">
          <el-select v-model="rateData.fgroupId" size="mini">
            <el-option v-for="item in treeData[0].childList" :key="item.fgroupId" :value="item.fgroupId" :label="item.fgroupName" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('market.fromcurr')" prop="fromcurrId">
          <el-autocomplete
            v-model.trim="rateData.fromcurrName"
            highlight-first-item
            popper-class="my-autocomplete"
            :fetch-suggestions="querySearch5"
            size="mini"
            @focus="queryTBdCurrency"
            @select="currencyData"
          >
            <template slot-scope="{ item }">
              <div class="name">{{ item.fname }}</div>
            </template>
          </el-autocomplete>
        </el-form-item>
        <el-form-item :label="$t('market.tocurr')" prop="tocurrId">
          <el-autocomplete
            v-model.trim="rateData.tocurrName"
            highlight-first-item
            popper-class="my-autocomplete"
            :fetch-suggestions="querySearch5"
            size="mini"
            @focus="queryTBdCurrency"
            @select="currencyData1"
          >
            <template slot-scope="{ item }">
              <div class="name">{{ item.fname }}</div>
            </template>
          </el-autocomplete>
        </el-form-item>
        <el-form-item :label="$t('market.exchangerate')" prop="exchangerate">
          <el-input-number
            v-model.number="rateData.exchangerate"
            :precision="4"
            controls-position="right"
            size="mini"
            @change="calculate(1)"
          />
        </el-form-item>
        <el-form-item :label="$t('market.contraryrate')" prop="contraryrate">
          <el-input-number
            v-model.number="rateData.contraryrate"
            :precision="4"
            controls-position="right"
            size="mini"
            @change="calculate(2)"
          />
        </el-form-item>
        <el-form-item :label="$t('market.starttime')" prop="starttime">
          <el-date-picker
            v-model="rateData.starttime"
            size="mini"
            type="date"
            value-format="yyyy-MM-dd"
            style="width: 163px"
            :placeholder="$t('market.checkDate')"
          />
        </el-form-item>
        <el-form-item :label="$t('market.endData')" prop="endtime">
          <el-date-picker
            v-model="rateData.endtime"
            size="mini"
            type="date"
            value-format="yyyy-MM-dd"
            style="width: 163px"
            :placeholder="$t('market.checkDate')"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="rateListVisable = false">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" size="mini" @click="insertRate">{{ $t('btn.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  queryBaseExchangeRateGroupList,
  insertBaseExchangeRateGroup,
  updateBaseExchangeRateGroup,
  delBaseExchangeRateGroup,
  queryExchangeRateList,
  insertExchangeRate,
  updateExchangeRate,
  delExchangeRate,
  notsubmitExchangeRateList,
  submitExchangeRateList,
  notreviewExchangeRateList,
  reviewExchangeRateList
} from '@/api/basicManagement/currencyRates'
import search from '@/components/Search'
import searData from '@/components/Search/mixin'
import jcButton from '@/components/Button'
import { toMxBmina } from '@/components/ToMxamineState'
import { export_json_to_excel, formatJson } from '@/utils/Export2Excel'
import autocomplete from '@/views/market/marketManage/createMarkerOrder/components/autocomplete'
export default {
  name: 'Rates',
  components: {
    search,
    jcButton
  },
  mixins: [searData, autocomplete],
  data() {
    return {
      ftype: 28,
      fbillNo: 'fgroupName',
      treeData: [
        {
          fgroupName: '全部',
          fgroupId: 0,
          childList: []
        }
      ],
      defaultProps: {
        children: 'childList',
        label: 'fgroupName'
      },
      rateTitle: '新增汇率组别',
      rateVisable: false, // 汇率分组弹窗
      rateTitle1: '新增汇率',
      rateListVisable: false, // 新增汇率弹窗
      groupData: {
        fgroupName: '',
        fnumber: ''
      },
      rateData: {
        fromcurrId: '',
        tocurrId: '',
        exchangerate: 0,
        contraryrate: 0,
        fgroupId: '',
        starttime: '',
        endtime: '',
        status: 'A'
      },
      tableData: [],
      tableHeader: [
        { label: this.$t('shop.numIndex'), prop: 'fid', width: '80' },
        { label: this.$t('market.groupname'), prop: 'fgroupName' },
        { label: this.$t('market.fromcurr'), prop: 'fromcurrName' },
        { label: this.$t('market.tocurr'), prop: 'tocurrName' },
        { label: this.$t('market.exchangerate'), prop: 'exchangerate' },
        { label: this.$t('market.contraryrate'), prop: 'contraryrate' },
        { label: this.$t('market.effectiveDate'), prop: 'starttime' },
        { label: this.$t('market.endData'), prop: 'endtime' },
        { label: this.$t('market.documentstatus'), type: 'tag', prop: 'fdocumentstatus' },
        // { label: this.$t('market.creator'), prop: 'fcreatorName' },
        // { label: this.$t('market.createDate'), prop: 'fcreateDate' },
        // { label: this.$t('market.lastmodifier'), prop: 'laupName' },
        // { label: this.$t('market.lastmodifyDate'), prop: 'lauptime' },
        // { label: '审核人姓名', prop: 'reviewName' },
        // { label: this.$t('market.approveDate'), prop: 'reviewDate' },
        { label: this.$t('market.handle'), type: 'btn' }
      ],
      tableHeight: '75vh',
      total: 0,
      currentPage: 1,
      size: 20
    }
  },
  created() {
    this.getMenuList() // 汇率分组
    this.getRateList() // 汇率列表
    this.tableHeader1 = this.tableHeader
  },
  methods: {
    // 菜单数据
    async getMenuList() {
      const { data: res } = await queryBaseExchangeRateGroupList({})
      this.treeData[0].childList = res
    },
    // 点击菜单
    handleNodeClick(data, node) {
      this.groupData = data
      this.fgroupId = data.fgroupId
      this.getRateList()
    },
    // 新增
    addGroup() {
      this.groupData = {
        fgroupName: '',
        fnumber: ''
      }
      this.rateVisable = true
      this.rateTitle = this.$t('market.addRateGroup') // '新增汇率组别'
    },
    // 修改
    editGroup() {
      this.rateVisable = true
      this.rateTitle = this.$t('market.editRateGroup') // '修改汇率组别'
    },
    insertGroup() {
      if (!this.groupData.fgroupId) {
        insertBaseExchangeRateGroup({ ...this.groupData }).then(res => {
          if (res.code === 0) {
            this.getMenuList()
            this.rateVisable = false
            this.$message({
              showClose: true,
              message: res.message,
              type: 'success'
            })
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
          }
        })
      } else {
        const DATA = {
          fgroupName: this.groupData.fgroupName,
          fnumber: this.groupData.fnumber,
          fgroupId: this.groupData.fgroupId
        }
        updateBaseExchangeRateGroup(DATA).then(res => {
          if (res.code === 0) {
            this.getMenuList()
            this.rateVisable = false
            this.$message({
              showClose: true,
              message: res.message,
              type: 'success'
            })
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
          }
        })
      }
    },
    // 删除
    delGroup() {
      this.$confirm('确认要删除么？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        delBaseExchangeRateGroup({ fgroupId: this.groupData.fgroupId }).then(res => {
          if (res.code === 0) {
            this.getMenuList()
            this.$message({ showClose: true, message: res.message, type: 'success' })
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
          }
        })
      })
    },
    // 汇率列表
    getRateList(ev) {
      this.details = []
      if (ev && !ev.page) {
        this.details = ev
      }
      const DATA = {
        fgroupId: this.fgroupId || 0,
        pageNum: this.currentPage,
        pageSize: this.size,
        search: this.searCollData.concat(this.details)
      }
      queryExchangeRateList(DATA).then(res => {
        if (res.code !== 0) {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            type: 'error'
          })
        }
        this.tableData = res.data.list.map(item => {
          return toMxBmina(item)
        })
        this.total = res.data.total
      })
    },
    // 新增汇率
    addRate() {
      this.rateData = {
        fromcurrId: '',
        tocurrId: '',
        exchangerate: 0,
        contraryrate: 0,
        fgroupId: this.fgroupId,
        starttime: '',
        endtime: '',
        status: 'A'
      }
      this.rateListVisable = true
      this.rateTitle1 = this.$t('market.addRate')
    },
    // 修改汇率
    editCurr(item) {
      this.rateListVisable = true
      this.rateTitle1 = this.$t('market.editRate')
      this.rateData = item
    },
    // 币别-原币
    currencyData(item) {
      this.rateData.fromcurrName = item.fname
      this.rateData.fromcurrId = item.fcurrencyId
    },
    // 币别-目标币
    currencyData1(item) {
      this.rateData.tocurrName = item.fname
      this.rateData.tocurrId = item.fcurrencyId
    },
    // 直接间接汇率
    calculate(ev) {
      if (ev === 1) { // 直接汇率
        this.rateData.contraryrate = (1 / this.rateData.exchangerate).toFixed(4)
      } else { // 间接汇率
        this.rateData.exchangerate = (1 / this.rateData.contraryrate).toFixed(4)
      }
    },
    // 搜索物料
    searchMaterialList(ev) {
      this.currentPage = 1
      if (ev && ev.fname) {
        this.customHandle(ev)
        this.getRateList(ev.detail)
      } else {
        this.getRateList()
      }
    },
    // 新增汇率
    insertRate() {
      if (!this.rateData.fid) { // 新增
        insertExchangeRate({ ...this.rateData }).then(res => {
          if (res.code === 0) {
            this.getRateList()
            this.rateListVisable = false
            this.$message({ showClose: true, message: res.message, type: 'success' })
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              type: 'error'
            })
          }
        })
      } else { // 修改
        const { fromcurrId, tocurrId, exchangerate, contraryrate, fgroupId, starttime, endtime, fid } = this.rateData
        const DATA = {
          fromcurrId, tocurrId, exchangerate, contraryrate, fgroupId, starttime, endtime, fid, status: 'A'
        }
        updateExchangeRate(DATA).then(res => {
          if (res.code === 0) {
            this.getRateList()
            this.rateListVisable = false
            this.$message({ showClose: true, message: res.message, type: 'success' })
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              type: 'error'
            })
          }
        })
      }
    },
    // 全选
    selectionDatas(val) {
      this.fids = []
      this.val = val
      val.forEach(item => {
        this.fids.push(item.fid + '')
      })
    },
    // 公共
    toExamineFun(api) {
      api({ Ids: this.fids }).then(res => {
        if (res.code === 0) {
          this.getRateList()
          this.fids = []
          this.innerHTM = ''
          res.data.forEach(res => {
            this.innerHTM += '<div>' + res + '</div>'
          })
          this.$notify.warning({
            title: '提示',
            message: this.innerHTM,
            duration: 3000, offset: 50,
            dangerouslyUseHTMLString: true
          })
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            type: 'error'
          })
        }
      })
    },
    // 提交
    submitRate(ev) {
      const api = ev === 1 ? submitExchangeRateList : notsubmitExchangeRateList
      this.toExamineFun(api)
    }, // 审核
    auditRate(ev) {
      const api = ev === 1 ? reviewExchangeRateList : notreviewExchangeRateList
      this.toExamineFun(api)
    },
    // 删除
    removeRate() {
      if (!this.val) {
        this.$message.warning('请选择要删除的汇率')
        return
      } else if (this.val && this.val.length > 1) {
        this.$message.warning('请选择一个你要删除的汇率')
        return
      }
      this.$confirm('确定要删除么？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        delExchangeRate({ fid: this.val[0].fid }).then(res => {
          if (res.code === 0) {
            this.getRateList()
            this.rateListVisable = false
            this.$message({ showClose: true, message: res.message, type: 'success' })
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              type: 'error'
            })
          }
        })
      })
    },
    // 导出表格-汇率
    handleExport() {
      require.ensure([], () => {
        const tHeader = this.tableHeader.map((res) => {
          return res.label
        })
        const filterVal = this.tableHeader.map((res) => {
          return res.prop
        })
        if (this.tableData.length <= 0) {
          this.$message.warning('没有导出数据')
        } else {
          queryExchangeRateList({
            pageSize: 100000,
            pageNum: 1,
            fgroupId: this.fgroupId,
            search: this.searCollData
          }).then(res => {
            if (res.code === 0) {
              const list = res.data.list.map(item => {
                return toMxBmina(item)
              })
              const data = formatJson(filterVal, list)
              export_json_to_excel(tHeader, data, '汇率列表')
            } else {
              this.$confirm(res.message, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'error'
              })
            }
          })
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.menulist {
  @include listBom;
  .header {
    position: relative;
    .header-name {
      width: 100%;
    }
    .btn {
      transform: translateY(18%);
      margin-left: 450px !important;
    }
  }
  .el-form {
    .el-form-item {
      height: 30px;
      width: 263px;
      margin-bottom: 15px;
    }
  }
  .rateContent {
    display: flex;
    flex-direction: row;
    width: 100%;
    margin-top: 5px;
    .sibarLeft {
      width: 20%;
      min-width: 270px;
      overflow: auto;
      border-right: 1px solid #eee;
    }
    .table-content {
      width: 80%;
      margin-left: 10px;
    }
  }
}
</style>
